var $, element, layer, laydate, form;

var chooseId = {};
var chooseItem = {};

var chooseIdArray = new Array(); // 选中的ID数组
var chooseItemArray = new Array(); // 选中的项目数组

layui.use(['jquery', 'element', 'layer', 'laydate', 'form', 'upload'], function () {
    // 加载元素控件
    $ = layui.jquery, element = layui.element, layer = layui.layer, laydate = layui.laydate, form = layui.form;

    $("input[name='room']").click(function (e) {
        $(".room-select-box-container").hide();
        $(this).parent().find(".room-select-box-container").show();
        init.initBusiness($(this));
        e.stopPropagation();
    });

    $(".room-box-container dd").click(function (e) {
        $(".room-select-box-container").hide();
    });

    $(document).click(function (event) {
        var e = e || window.event; //浏览器兼容性
        var elem = e.target || e.srcElement;
        while (elem) { //循环判断至跟节点，防止点击的是div子元素
            if (elem.id && elem.id == 'room-select-box-container') {
                return;
            }
            elem = elem.parentNode;
        }
        operate.chooseRoom($(".room-select-box-container:visible"));
        $(".room-select-box-container").hide();
    });

    // 项目复选框
    form.on('checkbox(cb-item)', function (data) {
        var obj = {};
        obj.id = data.value;
        obj.name = $(data.elem).parent().find("input").data('name');
        obj.area = $(data.elem).parent().find("input").data('area');
        if (!!$(data.elem).parent().find("input").data('wcode') && $(data.elem).parent().find("input").data('wcode') != undefined && $(data.elem).parent().find("input").data('wcode') != "undefined") {
            obj.wid = $(data.elem).parent().find("input").data('wcode');
        } else {
            obj.wid = "";
        }
        if (!!$(data.elem).parent().find("input").data('ecode') && $(data.elem).parent().find("input").data('ecode') != undefined && $(data.elem).parent().find("input").data('ecode') != "undefined") {
            obj.eid = $(data.elem).parent().find("input").data('ecode');
        } else {
            obj.eid = "";
        }
        var val = data.value;
        var title = data.elem.title;

        chooseIdArray = $.makeArray(chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
        chooseItemArray = $.makeArray(chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);

        if (data.elem.checked == true) {
            // console.log("项目：" + val + "选中了");
            chooseIdArray.push(val);
            chooseItemArray.push(obj);
            chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
            chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
        } else if (data.elem.checked == false) {
            // console.log("项目：" + val + "取消选中了");
            chooseIdArray = $.grep(chooseIdArray, function (value) {
                return value != val;
            });
            for (var j = 0; j < chooseItemArray.length; j++) {
                if (chooseItemArray[j].id == obj.id) {
                    chooseItemArray.splice(j, 1);
                    j--;
                }
            }
            chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
            chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
        }
    });
    // 楼层复选框
    form.on('checkbox(cb-floor)', function (data) {
        var val = data.value;
        var title = data.elem.title;
        chooseIdArray = $.makeArray(chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
        chooseItemArray = $.makeArray(chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
        if (data.elem.checked == true) {
            // console.log("楼层：" + val + "选中了");
            chooseIdArray.push(val);
            chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
        } else if (data.elem.checked == false) {
            // console.log("楼层：" + val + "取消选中了");
            chooseIdArray = $.grep(chooseIdArray, function (value) {
                return value != val;
            });
            $(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".room-box-container").find("input[name='cb-room']").each(function () {
                val = $(this).val();
                chooseIdArray = $.grep(chooseIdArray, function (value) {
                    return value != val;
                });
                for (var j = 0; j < chooseItemArray.length; j++) {
                    if (chooseItemArray[j].id == val) {
                        chooseItemArray.splice(j, 1);
                        j--;
                    }
                }
            });
            chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
            chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
        }
    });
    // 房间复选框
    form.on('checkbox(cb-room)', function (data) {
        var obj = {};
        obj.id = data.value;
        obj.name = $(data.elem).parent().find("input").data('name');
        obj.area = $(data.elem).parent().find("input").data('area');
        var val = data.value;
        var title = data.elem.title;
        chooseIdArray = $.makeArray(chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
        chooseItemArray = $.makeArray(chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
        if (data.elem.checked == true) {
            // console.log("房间：" + val + "选中了");
            chooseIdArray.push(val);
            chooseItemArray.push(obj);

            if ($(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".room-box-container").find("input[name='cb-room']").length == $(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".room-box-container").find("input[name='cb-room']:checked").length) {
                $(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".floor-box-container").find(".layui-this").find("input[name='cb-floor']").prop("checked", true);
                form.render();
                $(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".floor-box-container").find(".layui-this").find(".layui-form-checkbox").addClass("layui-form-checked");
                chooseIdArray.push($(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".floor-box-container").find(".layui-this").find("input[name='cb-floor']").val());
                chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
                chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
                window.event.stopPropagation();
            } else {
                chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
                chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
            }
        } else if (data.elem.checked == false) {
            // console.log("房间：" + val + "取消选中了");
            chooseIdArray = $.grep(chooseIdArray, function (value) {
                return value != val;
            });
            for (var j = 0; j < chooseItemArray.length; j++) {
                if (chooseItemArray[j].id == obj.id) {
                    chooseItemArray.splice(j, 1);
                    j--;
                }
            }
            $(data.elem).parent().parent().parent().parent().parent().parent().parent().find(".floor-box-container").find(".layui-this").find("input[name='cb-floor']").removeAttr("checked");
            form.render('checkbox');
            chooseIdArray = $.grep(chooseIdArray, function (value) {
                return value != $(".floor-box-container").find(".layui-this").data('id');
            });
            chooseId["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseIdArray;
            chooseItem["item" + $(data.elem).parent().parent().parent().parent().parent().parent().parent().attr("data-index")] = chooseItemArray;
            window.event.stopPropagation();
        }
    });

});
/**
 * 初始化方法集合
 * 使用： init.function()
 * param: obj传this，调用该方法的对象
 *
 */
var init = {
    // 初始化房间下拉框商圈
    initBusiness: function (obj) {
        $.ajax({
            url: "/business/list",
            data: {},
            dataType: "json",
            type: "post",
            async: false,
            success: function (res) {
                if (res.errcode === "0") {
                    $(obj).parent().find(".business-box-container").empty();
                    if (res.data.length > 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            if (res.data[i].IS_OPEN === "on") {
                                var str = '<dd data-id="' + res.data[i].ID + '" title="' + res.data[i].BUSINESS_NAME + '">' + res.data[i].BUSINESS_NAME + '</dd>';
                                $(obj).parent().find(".business-box-container").append(str);
                            }
                        }
                    }
                    $(obj).parent().find(".business-box-container dd").click(function (e) {
                        $(this).addClass('layui-this').siblings().removeClass("layui-this");
                        init.initBuilding($(this).data("id"), $(obj));
                        $(obj).parent().find(".building-box-container").show();
                        $(obj).parent().find(".unit-box-container").hide();
                        $(obj).parent().find(".floor-box-container").hide();
                        $(obj).parent().find(".room-box-container").hide();
                    });
                } else if (res.errcode === "1") {
                    layer.msg(res.errmsg, function () {
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.error(XMLHttpRequest.status);
                console.error(XMLHttpRequest.readyState);
                console.error(textStatus);
            }
        });
    },
    // 初始化房间下拉框楼宇
    initBuilding: function (businessId, obj) {
        $.ajax({
            url: "/building/list",
            data: {BUSINESS_ID: businessId},
            dataType: "json",
            type: "post",
            async: false,
            success: function (res) {
                if (res.errcode === "0") {
                    $(obj).parent().find(".building-box-container").empty();
                    if (res.data.length > 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            if (res.data[i].IS_OPEN === "on") {
                                var str = '<dd data-id="' + res.data[i].BUILDING_ID + '" title="' + res.data[i].BUILDING_NAME + '">' + res.data[i].BUILDING_NAME + '</dd>';
                                $(obj).parent().find(".building-box-container").append(str);
                            }
                        }
                    }
                    $(obj).parent().find(".building-box-container dd").click(function (e) {
                        $(this).addClass('layui-this').siblings().removeClass("layui-this");
                        init.initUnit($(this).data("id"), $(obj));
                        $(obj).parent().find(".unit-box-container").show();
                        $(obj).parent().find(".floor-box-container").hide();
                        $(obj).parent().find(".room-box-container").hide();
                    });
                } else if (res.errcode === "1") {
                    layer.msg(res.errmsg, function () {
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.error(XMLHttpRequest.status);
                console.error(XMLHttpRequest.readyState);
                console.error(textStatus);
            }
        });
    },
    // 初始化房间下拉框单元
    initUnit: function (buildingId, obj) {
        $.ajax({
            url: "/building/info",
            data: {BUILDING_ID: buildingId},
            dataType: "json",
            type: "post",
            async: false,
            success: function (res) {
                if (res.errcode === "0") {
                    $(obj).parent().find(".unit-box-container").empty();
                    if (res.unitList.length > 0) {
                        for (var i = 0; i < res.unitList.length; i++) {
                            if (res.unitList[i].IS_OPEN === "on") {
                                var str = '<dd class="dd-unit" data-id="' + res.unitList[i].UNIT_ID + '" title="' + res.unitList[i].UNIT_NAME + ' 单元">' + res.unitList[i].UNIT_NAME + ' 单元</dd>';
                                $(obj).parent().find(".unit-box-container").append(str);
                            }
                        }
                    }
                    if (res.itemList.length > 0) {
                        for (var i = 0; i < res.itemList.length; i++) {
                            var chooseFlag = "";
                            chooseIdArray = $.makeArray(chooseId["item" + $(obj).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
                            chooseItemArray = $.makeArray(chooseItem["item" + $(obj).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
                            $.each(chooseIdArray, function (index, value) {
                                if (res.itemList[i].ROOM_ID == value) {
                                    chooseFlag = "checked";
                                }
                            });
                            var str = '<dd class="dd-item" data-area="' + res.itemList[i].ROOM_AREA + '" data-id="' + res.itemList[i].ROOM_ID + '" title="【' + res.itemList[i].ROOM_TYPE_NAME + '】' + res.itemList[i].ROOM_NUM + '"><input type="checkbox" name="cb-item" value="' + res.itemList[i].ROOM_ID + '" data-name="' + res.itemList[i].ROOM_NUM + '" data-area="' + res.itemList[i].ROOM_AREA + '" data-wcode="' + res.itemList[i].WATER_CODE + '" data-ecode="' + res.itemList[i].ELECTRIC_CODE + '" ' + chooseFlag + ' lay-filter="cb-item" lay-skin="primary">【' + res.itemList[i].ROOM_TYPE_NAME + '】' + res.itemList[i].ROOM_NUM + '</dd>';
                            $(obj).parent().find(".unit-box-container").append(str);
                        }
                    }
                    form.render();
                    $(obj).parent().find(".unit-box-container dd.dd-unit").click(function (e) {
                        $(this).addClass('layui-this').siblings().removeClass("layui-this");
                        $(obj).parent().find(".floor-box-container").show();
                        $(obj).parent().find(".room-box-container").hide();
                        init.initFloor($(this).data("id"), $(obj));
                    });
                    $(obj).parent().find(".unit-box-container dd.dd-item").click(function (e) {
                        $(this).siblings().removeClass("layui-this");
                        $(obj).parent().find(".floor-box-container").hide();
                        $(obj).parent().find(".room-box-container").hide();
                    });
                } else if (res.errcode === "1") {
                    layer.msg(res.errmsg, function () {
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.error(XMLHttpRequest.status);
                console.error(XMLHttpRequest.readyState);
                console.error(textStatus);
            }
        });
    },
    // 初始化房间下拉框楼层
    initFloor: function (unitId, obj) {
        $.ajax({
            url: "/building/floorInfo",
            data: {UNIT_ID: unitId},
            dataType: "json",
            type: "post",
            async: false,
            success: function (res) {
                if (res.errcode === "0") {
                    $(obj).parent().find(".floor-box-container").empty();
                    if (res.data.length > 0) {
                        for (var i = res.data.length - 1; i >= 0; i--) {
                            chooseIdArray = $.makeArray(chooseId["item" + $(obj).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
                            chooseItemArray = $.makeArray(chooseItem["item" + $(obj).parent().parent().parent().parent().parent().parent().parent().attr("data-index")]);
                            var chooseFlag = "";
                            $.each(chooseIdArray, function (index, value) {
                                if (res.data[i].FLOOR_ID == value) {
                                    chooseFlag = "checked";
                                }
                            });
                            if (res.data[i].IS_OPEN === "on") {
                                var str = '<dd data-id="' + res.data[i].FLOOR_ID + '" data-bid="' + res.data[i].BUILDING_ID + '" title="' + res.data[i].FLOOR_NAME + ' 层"><input type="checkbox" name="cb-floor" value="' + res.data[i].FLOOR_ID + '" lay-filter="cb-floor" lay-skin="primary" ' + chooseFlag + '> ' + res.data[i].FLOOR_NAME + ' 层</dd>';
                                $(obj).parent().find(".floor-box-container").append(str);
                            }
                        }
                    }
                    form.render();
                    $(obj).parent().find(".floor-box-container dd").click(function (e) {
                        $(this).addClass('layui-this').siblings().removeClass("layui-this");
                        init.initRoom($(this).data("bid"), $(this).data("id"), $(obj));
                        $(obj).parent().find(".room-box-container").show();
                        e.stopPropagation();
                    });
                } else if (res.errcode === "1") {
                    layer.msg(res.errmsg, function () {
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.error(XMLHttpRequest.status);
                console.error(XMLHttpRequest.readyState);
                console.error(textStatus);
            }
        });
    },
    // 初始化房间下拉框房间
    initRoom: function (buildingId, floorId, objj) {
        $.ajax({
            url: "/room/list",
            data: {BUILDING_ID: buildingId, FLOOR_ID: floorId},
            dataType: "json",
            type: "post",
            async: false,
            success: function (res) {
                if (res.errcode === "0") {
                    $(objj).parent().find(".room-box-container").empty();
                    chooseIdArray = $.makeArray(chooseId["item" + $(objj).parent().parent().attr("data-index")]);
                    chooseItemArray = $.makeArray(chooseItem["item" + $(objj).parent().parent().attr("data-index")]);
                    var chooseFlag = "";
                    $.each(chooseIdArray, function (index, value) {
                        if (floorId == value) {
                            chooseFlag = "checked";
                        }
                    });
                    if (chooseFlag == "checked") {
                        for (var i = 0; i < res.data.length; i++) {
                            chooseIdArray = $.grep(chooseIdArray, function (value) {
                                return value != res.data[i].ROOM_ID;
                            });
                            for (var j = 0; j < chooseItemArray.length; j++) {
                                if (chooseItemArray[j].id == res.data[i].ROOM_ID) {
                                    chooseItemArray.splice(j, 1);
                                    j--;
                                }
                            }
                        }
                        for (var i = 0; i < res.data.length; i++) {
                            chooseIdArray.push(res.data[i].ROOM_ID);
                            var obj = {};
                            obj.id = res.data[i].ROOM_ID;
                            obj.name = res.data[i].ROOM_NUM;
                            obj.area = res.data[i].ROOM_AREA;
                            if (!!res.data[i].WATER_CODE && res.data[i].WATER_CODE != undefined && res.data[i].WATER_CODE != "undefined") {
                                obj.wid = res.data[i].WATER_CODE;
                            } else {
                                obj.wid = "";
                            }
                            if (!!res.data[i].ELECTRIC_CODE && res.data[i].ELECTRIC_CODE != undefined && res.data[i].ELECTRIC_CODE != "undefined") {
                                obj.eid = res.data[i].ELECTRIC_CODE;
                            } else {
                                obj.eid = "";
                            }
                            chooseItemArray.push(obj);
                        }
                        chooseId["item" + $(objj).parent().parent().attr("data-index")] = chooseIdArray;
                        chooseItem["item" + $(objj).parent().parent().attr("data-index")] = chooseItemArray;
                    }
                    if (res.data.length > 0) {
                        for (var i = 0; i < res.data.length; i++) {
                            var chooseFlag1 = "";
                            $.each(chooseIdArray, function (index, value) {
                                if (res.data[i].ROOM_ID == value) {
                                    chooseFlag1 = "checked";
                                }
                            });
                            if (res.data[i].IS_OPEN === "on") {
                                var str = '<dd data-id="' + res.data[i].ROOM_ID + '" data-wcode="' + res.data[i].WATER_CODE + '" data-ecode="' + res.data[i].ELECTRIC_CODE + '" data-area="' + res.data[i].ROOM_AREA + '" title="' + res.data[i].ROOM_NAME + '"><input type="checkbox" name="cb-room" value="' + res.data[i].ROOM_ID + '" data-name="' + res.data[i].ROOM_NUM + '" data-area="' + res.data[i].ROOM_AREA + '" data-wcode="' + res.data[i].WATER_CODE + '" data-ecode="' + res.data[i].ELECTRIC_CODE + '" lay-filter="cb-room" lay-skin="primary" ' + chooseFlag1 + '> ' + res.data[i].ROOM_NUM + '</dd>';
                                $(objj).parent().find(".room-box-container").append(str);
                            }
                        }
                    }
                    form.render();
                    // 已经选择的不可以再次选择
                    $("input[name='room']").each(function () {
                        var id = $(this).attr('data-id');
                        if (!!id) {
                            $(objj).parent().find(".room-box-container").find("dd").each(function () {
                                if ($(this).attr('data-id') == id) {
                                    $(this).remove();
                                }
                            });
                        }
                    });
                } else if (res.errcode === "1") {
                    layer.msg(res.errmsg, function () {
                    });
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.error(XMLHttpRequest.status);
                console.error(XMLHttpRequest.readyState);
                console.error(textStatus);
            }
        });
    }
};
/**
 * 操作方法集合
 * 使用： operate.function()
 * param: obj传this，调用该方法的对象
 *
 */
var operate = {
    // 选择完房间项目确认
    chooseRoom: function (obj) {
        var str = "";
        $.each(chooseItem["item" + $(obj).parent().parent().parent().attr("data-index")], function (index, value) {
            if (index == 0) {
                str += value.name;
            } else {
                str += "," + value.name;
            }
        });
        $(obj).parent().parent().find("input[name='room']").val(str);
    },
    // 克隆方法
    clone: function (obj) {
        var a = $(obj).parent().parent().find(".clone-box:last");
        //console.log(a)
        var index = $(a).attr("data-index");
        var b = a.clone(true);
        $(b).attr("data-index", parseInt(index) + 1);
        $(b).find(".fa-plus-circle").hide();
        $(b).find(".fa-times-circle").show();

        $(b).find("input[name='room']").val("");
        $(b).find("input[name='room']").attr("data-id", "");
        $(b).find(".box-container dd").removeClass("layui-this");
        $(b).find(".building-box-container").empty();
        $(b).find(".building-box-container").hide();
        $(b).find(".unit-box-container").empty();
        $(b).find(".unit-box-container").hide();
        $(b).find(".floor-box-container").empty();
        $(b).find(".floor-box-container").hide();
        $(b).find(".room-box-container").empty();
        $(b).find(".room-box-container").hide();
        $(b).find("input[type='checkbox']").each(function () {
            $(this).prop("checked", false);
        });
        $(obj).parent().parent().append(b);

        form.render();
    },
    // 移除当前信息的方法，tier为几层父级
    remove: function (obj, tier) {
        switch (tier) {
            case 1:
                $(obj).parent().remove();
                break;
            case 2:
                $(obj).parent().parent().remove();
                break;
            case 3:
                $(obj).parent().parent().parent().remove();
                break;
        }
    },
    console: function () {
       console.log(chooseId);
        console.log(chooseItem);
    }
};